package com.rtx.edi.platform.express.auth.handler;

import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.model.express.auth.po.PlAuthApp;
import com.rtx.edi.model.express.auth.po.PlAuthShopApp;
import com.rtx.edi.model.express.auth.po.PlExpressSubscription;
import com.rtx.edi.platform.express.auth.mapper.PlAuthShopAppMapper;
import com.rtx.edi.platform.express.auth.service.PlAuthAppService;
import com.rtx.edi.platform.express.auth.service.PlAuthShopAppService;
import com.rtx.edi.platform.express.auth.service.PlExpressSubscriptionService;
import com.rtx.edi.platform.express.auth.service.WaybillService;
import com.taobao.api.response.CainiaoWaybillIiSearchResponse;
import com.taobao.api.response.CainiaoWaybillIiSearchResponse.AddressDto;
import com.taobao.api.response.CainiaoWaybillIiSearchResponse.WaybillApplySubscriptionInfo;
import com.taobao.api.response.CainiaoWaybillIiSearchResponse.WaybillBranchAccount;

/**
 * 获取授权订购关系 
 * @author luoqiongli
 *
 */
@Component
public class ExpressSubscriptionHandler {

	@Autowired
	private PlAuthAppService plAuthAppService;
	
	@Autowired
	private PlAuthShopAppService shopappService;
	
	
	@Autowired
	private WaybillService waybillService;
	
	@Autowired
	private PlExpressSubscriptionService plExpressSubscriptionService;
	
	 public void handler() throws Exception{
		 
		 LambdaQueryWrapper<PlAuthShopApp> query= Wrappers.lambdaQuery();
		 query.eq(PlAuthShopApp::getActive, "1")
		 .eq(PlAuthShopApp::getDeleteflag, "0");
		 List<PlAuthShopApp> reqList= shopappService.getBaseMapper().selectList(query);
		 for (PlAuthShopApp vo : reqList) {
			 PlAuthApp app= plAuthAppService.getById(vo.getAppid());
			 String type=app.getType(); // 应用所属平台
			 switch (type) {
			 	case "TB":
			 		CainiaoWaybillIiSearchResponse response = waybillService.getTbWaybill(app.getGetway(), app.getAppkey(), app.getAppsecret(),vo.getAuthcode(), null);
			 		analysisTbresp(response);
			 		break;
				case "DY":

					break;
				case "PDD":
					
					break;
				case "JD":
					
					break;
				case "XHS":
					
					break;
				case "DW":
					
					break;
				default:
					
					break;
				}
			 
		}
		  
	 }
	 
	 /**
	  * 解析淘宝返回报文
	  * @param resp
	  */
	 private void analysisTbresp(CainiaoWaybillIiSearchResponse resp) {
		 
		 if( resp.getWaybillApplySubscriptionCols()!=null) {
			 List<WaybillApplySubscriptionInfo> waybillApplySubscriptionCols=resp.getWaybillApplySubscriptionCols();
			 for (WaybillApplySubscriptionInfo info : waybillApplySubscriptionCols) {
				 for (WaybillBranchAccount account : info.getBranchAccountCols()) {
					  
					 for(AddressDto dto:account.getShippAddressCols()) {
						 PlExpressSubscription subscription=new PlExpressSubscription();
						 subscription.setSalesp("TB"); // 平台
						 subscription.setCpcode( info.getCpCode()); // 物流服务商id
						 subscription.setCptype(String.valueOf(info.getCpType())); // 物流服务商业务类型
						 subscription.setQty(account.getQuantity());
						 subscription.setBranchcode(account.getBranchCode()); // 网点 
						 subscription.setBranchname(account.getBranchName()); // 网点名称
						 subscription.setDetail(dto.getDetail());  // 详细地址
						 subscription.setDistrict(dto.getDistrict()); // 区名称（三级地址）
						 subscription.setCity(dto.getCity()); // 市名称（二级地址）
						 subscription.setProvince(dto.getProvince()); // 省名称（一级地址）
						 subscription.setTown(dto.getTown()); // 街道\镇名称（四级地址）
//						 subscription.setBrandcode(account.getBrandCode()); // 品牌code
						 String customercodes="";
//						 for(String str:account.getCustomerCodeList()) {
//							 customercodes+=str+",";
//						 }
						 if(!"".equals(customercodes) &&customercodes.indexOf(",")!=-1) {
							 subscription.setCustomercodes(customercodes.substring(0,customercodes.lastIndexOf(","))); // 月结卡号
						 }else {
							 subscription.setCustomercodes(customercodes);
						 }
						 
						 subscription.setAddwho("ris_edi_dev");
						 subscription.setEditwho("ris_edi_dev");
						 
						 // 不存在新增 存在更新 
						 QueryWrapper<PlExpressSubscription> qw =new QueryWrapper<PlExpressSubscription>();
						 qw.eq("salesp", "TB");
						 qw.eq("cpcode", info.getCpCode());
						 qw.eq("cptype", String.valueOf(info.getCpType()));
						 qw.eq("branchcode", account.getBranchCode());
						 qw.eq("branchname", account.getBranchName());
//						 qw.eq("brandcode", account.getBrandCode());
						 
						boolean isexist= plExpressSubscriptionService.getBaseMapper().exists(qw);
						if(isexist) {
							PlExpressSubscription old =plExpressSubscriptionService.getOne(qw);
							subscription.setId(old.getId());
							BeanUtils.copyProperties(subscription,old);
							plExpressSubscriptionService.updateById(old);
						}else {
							// 新增
							plExpressSubscriptionService.addPlExpressSubscription(subscription);
						}
						 
					 }
				}
 
			}

		 }
		 
	 }
	
	
}
